﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using LinqToLdap;
using LinqToLdap.Collections;
using LINQtoLDAPDemo_Model;

namespace LINQtoLDAPDemo_Winform.Models
{
    public class NorthwindDAO
    {
        #region Private Variables
        private int pageSize = 10;
        private Group currentGroup;
        private ILdapPage<User>[] nonMemberPageContents, memberPageContents;
        #endregion

        #region Properties
        public int NonMemberPageNum { get; private set; }
        public int MemberPageNum { get; private set; }
        #endregion

        #region Constructor
        public NorthwindDAO()
        {
            ResetCurrentPageNumbers();
        }
        #endregion

        private void ResetCurrentPageNumbers()
        {
            NonMemberPageNum = 1;
            MemberPageNum = 1;
        }

        public User[] GetPageContents(bool _isMember)
        {
            return _isMember ? memberPageContents[MemberPageNum - 1].ToArray() : nonMemberPageContents[NonMemberPageNum - 1].ToArray();
        }

        public int GetTotalNumberOfPages(bool _isMember)
        {
            return _isMember ? memberPageContents.Count() : nonMemberPageContents.Count();
        }
        
        public void SetCurrentGroup(Group _group)
        {
            if (_group != null)
            {
                currentGroup = _group;
                RefreshUserData();
                ResetCurrentPageNumbers();
            }
        }

        public void RefreshUserData()
        {
            nonMemberPageContents = Group.GetUserPagesByGroupMembershipStatus(currentGroup, pageSize, false).ToArray();
            memberPageContents = Group.GetUserPagesByGroupMembershipStatus(currentGroup, pageSize, true).ToArray();

            if (nonMemberPageContents.Count() < NonMemberPageNum)
                NonMemberPageNum = nonMemberPageContents.Count();

            if (memberPageContents.Count() < MemberPageNum)
                MemberPageNum = memberPageContents.Count();
        }

        public bool ChangeToValidPageNumber(string _input, bool _isMember)
        {
            int parsedInput;

            if (int.TryParse(_input, out parsedInput))
            {
                if (_isMember && (parsedInput <= memberPageContents.Count() && parsedInput > 0))
                {
                    MemberPageNum = parsedInput;
                    return true;
                }
                else if (!_isMember && (parsedInput <= nonMemberPageContents.Count() && parsedInput > 0))
                {
                    NonMemberPageNum = parsedInput;
                    return true;
                }
            }

            return false;
        }
    }
}
